<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <!-- 基本信息 -->

        <a-row :gutter="48">
          <a-col :span="8" :hidden="true">
            <a-form-model-item label="流程名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle" >
              <a-input :max-length="255" :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入流程名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="单据编号">
              <a-input placeholder="请输入单据编号" v-model="model.billNo" disabled></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <j-date
                placeholder="请选择申请时间"
                v-model="model.createTime"
                :show-time="true"
                date-format="YYYY-MM-DD HH:mm"
                style="width: 100%"
                disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlerId">
              <select-user-by-dep :multi="false" v-model="model.handlerId" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlerDeptId">
              <j-select-depart v-model="model.handlerDeptId" disabled/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="项目信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
                  <select-project-distribution-input
                    :disabled="formDisabled"
                    projectStatus="2"
                    :proDisabled="true"
                    :isContractManager="true"
                    v-model="model.projectId"
                    placeholder="请选择项目名称"
                    @input="onChangeProjectName"></select-project-distribution-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="finalNo">
                  <a-input disabled v-model="model.finalNo" placeholder="请输入项目编号"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="经营团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamName">
                  <select-team-input
                    disabled
                    v-model="model.teamName"
                    :tdlx="1"/>

                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目承接人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="undertaker">
                  <select-user-by-dep disabled v-model="model.undertaker" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="立项日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectEstablishDate">
                  <j-date
                    disabled
                    placeholder="请选择立项日期"
                    v-model="model.projectEstablishDate"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="签订单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="signUnit">
                  <select-Company-input placeholder="请输入签订单位" disabled v-model="model.signUnit"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="业绩归属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
                  <j-dict-select-tag
                    disabled
                    type="list"
                    v-model="model.year"
                    dictCode="yjgsnd"
                    placeholder="请选择业绩归属年度"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="业主单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ownerUnit">
                  <select-customer-input
                    disabled
                    v-model="model.ownerUnit"
                    commercialType="1"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contacts">
                  <j-dict-select-tag
                    disabled
                    type="list"
                    v-model="model.contacts"
                    :dictCode="cust_lxr"
                    placeholder="请选择联系人"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="联系方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contactTel">
                  <a-input disabled v-model="model.contactTel" placeholder="请输入联系电话"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" >
                <a-form-model-item prop="areaCode" label="项目所在地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <AddressChoice disabled type="cascader" v-model="model.areaCode" placeholder="请输入省市区" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item prop="projectAddress" label="项目详细地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input disabled v-model="model.projectAddress" placeholder="请输入项目详细地址"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目来源" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectSource">
                  <j-dict-select-tag
                    disabled
                    type="list"
                    v-model="model.projectSource"
                    dictCode="xmly_type"
                    placeholder="请选择项目来源"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="预计合同额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="estimatedContractAmount">
                  <a-input-number
                    disabled
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.estimatedContractAmount"
                    placeholder="请输入预计合同额"
                    style="width: 100%"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="预计合同额大写" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="estimatedContractcapitalChineseAmount">
                  <a-input disabled v-model="model.estimatedContractcapitalChineseAmount" placeholder="请输入预计合同额大写"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="立项事由及说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="establishReason">
                  <a-textarea :max-length="500" disabled v-model="model.establishReason" rows="4" placeholder="请输入立项事由及说明"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="项目附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.attachment"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.attachment)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="需分配任务信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <!-- @back="changeTask" -->
                <a-form-model-item label="任务编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taskId">
                  <SelectTaskFileInput
                    :disabled="formDisabled"
                    v-model="model.taskId"
                    :projectId="model.projectId"
                    @input="onTaskIdInput"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="业务分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryName">
                  <a-input
                    :disabled="formDisabled"
                    v-model="model.categoryName"
                    placeholder="请选择业务分类" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同占比(%)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractRate">
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.contractRate"
                    placeholder="请输入合同占比"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同分配额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractAmount">
                  <a-input-number
                  
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.contractAmount"
                    placeholder="请输入合同分配额"
                    style="width: 100%"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="切割合同额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">
                  <a-input-number
                    disabled
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.cutContractAmount"
                    placeholder="请输入切割合同额"
                    style="width: 100%"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="生产团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productTeam">
                  <select-team-input
                    :disabled="formDisabled"
                    v-model="model.productTeam"
                    :tdlx="2"
                    :triggerChange="true"/>
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="需分配合同额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="separateContractAmount">
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.separateContractAmount"
                    placeholder="请输入需分配合同额"
                    style="width: 100%"
                    @blur="handleChangeSeparateContractAmount"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="需分配切割合同额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="needCutContractAmount">
                  <a-input-number
                    disabled
                    :min="0"
                    :precision="2"
                    v-model="model.needCutContractAmount"
                    placeholder="请输入需分配切割合同额"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="是否作废" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isCancel">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="radio"
                    v-model="model.isCancel"
                    dictCode="YES_OR_NO"
                    placeholder="请选择是否作废"
                    @change="handleChangeIsCancel"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reason">
                  <a-textarea :max-length="500" :disabled="formDisabled" v-model="model.reason" rows="4" placeholder="请输入说明"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="任务附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="file">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.file"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.file)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="新增分配任务信息">
            <a-row :gutter="48">
              <a-col :span="24" >
                <div style="margin-bottom: 6px;margin-top: 6px" >
                  <a-button @click="handleMemberAdd" v-if="!formDisabled" type="primary">新增</a-button>
                </div>
                <a-table
                  ref="table"
                  size="middle"
                  rowKey="id"
                  :loading="memberLoading"
                  :columns="memberColumns"
                  bordered
                  :components="draggableComponent"
                  :pagination="false"
                  :data-source="model.redistributionDtList"
                  :scroll="{x: scrollX}"
                >
                  <span slot="action" slot-scope="text, record">
                    <template v-if="!formDisabled">
                      <a-button
                        class="ruleButton"
                        :ghost="true"
                        type="primary"
                        icon="edit"
                        @click="handleMemberEdit(record)"/>
                      <a-divider type="vertical"/>
                      <a-popconfirm title="确定删除吗?" @confirm="() => handleMemberDelete(record.id)">
                        <a-button
                          class="ruleButton"
                          :ghost="true"
                          type="primary"
                          icon="delete"
                        />
                      </a-popconfirm>
                    </template>
                  </span>
                </a-table>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="4" header="需分配款项信息">
            <a-row :gutter="48">
              <a-col :span="24" >
                <a-table
                  ref="table"
                  size="middle"
                  rowKey="index"
                  bordered
                  :components="draggableComponent"
                  :loading="receivablePaymentLoading"
                  :columns="paymentProgressColumns"
                  :pagination="false"
                  :data-source="progressNodeVoList"
                  :scroll="{ x: scrollX }"
                >
                  <span slot="action" slot-scope="text, record">
                    <template>
                      <a @click="handleDetail(record)">查看</a>
                    </template>
                  </span>
                </a-table>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
      <view-file-modal ref="viewFileModal"></view-file-modal>
    </j-form-container>
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <!-- <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button> -->
      </a-col>
    </a-row>
    <ErpOmcTaskRedistributionFormPrint id="taskContent" v-if="formBpm" class="print_style" :formData="model" :formDataHistory="formData"></ErpOmcTaskRedistributionFormPrint>
    <ErpOmcTaskRedistributionMemberModal ref="memberList" :contractAmount="model.contractAmount" @ok="submitCallback" />
    <ErpOmcTaskRedistributionPaymentModal
      ref="paymentModal"
      :estimatedContractAmount="model.estimatedContractAmount"
      :separateContractAmount="model.separateContractAmount"
      :redistributionDtList="paymentTaskList"
      :projectId="model.projectId" />
  </a-spin>
</template>

<script>

import { getAction, httpAction } from '@/api/manage'
import { viewFile } from '@/utils/util'
import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
import ViewFileModal from '@/views/scy/components/ViewFileModal'
import {
  filterMultiDictText,
  initDictOptions
} from '@/components/dict/JDictSelectUtil'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
import AddressChoice from '@/components/AddressChoice/AddressChoice';
import { mapGetters } from 'vuex';
import moment from 'moment';
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import Print from '@/utils/print/printarea.js';
import ErpOmcTaskRedistributionFormPrint from './ErpOmcTaskRedistributionFormPrint' // 打印
import SelectProjectDistributionInput from '@/views/scy/components/SelectProjectDistributionInput'; //  项目名称
import SelectTaskFileInput from '@/views/scy/components/SelectTaskFileInput'; //  任务编号
import SelectProcessTemplateInput from '@/views/scy/components/SelectProcessTemplateInput' // 进度模板
import ErpOmcTaskRedistributionMemberModal from './reference/ErpOmcTaskRedistributionMemberModal' // 新增分配任务信息
import { DragResizable } from '@/mixins/DragResizable'
import ErpOmcTaskRedistributionPaymentModal from './reference/ErpOmcTaskRedistributionPaymentModal' // 需分配款项信息
import Decimal from 'decimal.js'
export default {
  name: 'ErpOmcTaskRedistributionForm',
  mixins: [DisabledAuthFilterMixin, viewFile, DragResizable],
  components: {
    ViewFileModal,
    SelectUserByDep,
    SelectTeamInput,
    SelectCustomerInput,
    AddressChoice,
    SelectCompanyInput,
    CommonFlowList,
    ErpOmcTaskRedistributionFormPrint,
    SelectProjectDistributionInput, //  项目名称
    SelectTaskFileInput, // 任务编号
    SelectProcessTemplateInput, // 进度模板
    ErpOmcTaskRedistributionMemberModal,
    ErpOmcTaskRedistributionPaymentModal
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    taskId: {
      type: String,
      default: '',
      required: false
    },
    projectNameId: {
      type: String,
      default: '',
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      paymentTaskList: [], // 任务委托数据
      memberLoading: false,
      activeKey: ['1', '2', '3', '4', '5', '6'],
      tableNoData: { emptyText: () => (
        <a-empty description="合同未签订，暂无数据" />
      ) },
      templateLoading: false,
      progressNodeVoLoading: false,

      model: {
        redistributionDtList: [],
        dataSource: [],
        handlerId: undefined,
        handlerDeptId: undefined,
        createTime: undefined,
        undertaker: undefined
      },
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      templateDataList: [], // 进度模板列表
      progressNodeVoList: [], // 款项进度列表
      confirmLoading: false,
      validatorRules: {
        projectId: [
          { required: true, message: '请选择项目名称!', pattern: '[^ \x22]+' }
        ],
        separateContractAmount: [
          { required: true, message: '请输入需分配合同额!' }
        ],
        isCancel: [
          { required: true, message: '请选择是否作废!' }
        ],
        categoryName: [
          { required: true, message: '请选择业务分类!' }
        ],
        contractRate: [
          { required: true, message: '请输入需分配合同额!' }
        ],
        contractAmount: [
          { required: true, message: '请输入需分配合同额!' }
        ],
        productTeam: [
          { required: true, message: '请输入需分配合同额!' }
        ]
      },
      url: {
        add: '/api/erp/task/erpOmcTaskRedistribution/add',
        edit: '/api/erp/task/erpOmcTaskRedistribution/edit',
        queryById: '/api/erp/task/erpOmcTaskRedistribution/queryById',
        erpOmcProjectQueryById: '/api/erp/omc/project/erpOmcProject/queryById',
        queryPageList: '/api/erp/omc/project/erpOmcProjectTaskFinal/queryPageList',
        generatedFormNumber: '/api/erp/base/generatedFormNumber'
      },
      loading: false,
      memberColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '业务分类',
          align: 'center',
          dataIndex: 'categoryName',
          width: 240,
          ellipsis: true
        },
        {
          title: '合同占比(%)',
          align: 'center',
          dataIndex: 'contractRate',
          width: 120,
          ellipsis: true
        },
        {
          title: '合同分配额(元)',
          align: 'center',
          dataIndex: 'contractAmount',
          width: 130,
          ellipsis: true
        },
        {
          title: '切割合同额(元)',
          align: 'center',
          dataIndex: 'cutContractAmount',
          width: 130,
          ellipsis: true
        },
        {
          title: '生产团队',
          align: 'center',
          dataIndex: 'productTeam',
          width: 200,
          ellipsis: true,
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['productTeam'], text + '')
            }
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 150,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }
      ],
      // 进度列表
      templateColumns: [
        {
          title: '顺序',
          dataIndex: '',
          key: 'rowIndex',
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '节点名称',
          align: 'center',
          dataIndex: 'nodeName'
        },
        {
          title: '节点进度',
          align: 'center',
          dataIndex: 'nodeProgress',
          scopedSlots: { customRender: 'titleSlot' }
        }
      ],

      // 款项进度
      paymentProgressColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '款项名称',
          align: 'center',
          dataIndex: 'paymentName'
        },
        {
          title: '款项节点说明',
          align: 'center',
          dataIndex: 'paymentDesc'
        },
        {
          title: '款项关联任务',
          align: 'center',
          dataIndex: 'taskId_dictText'
        },
        {
          title: '需分配款项金额(元)',
          align: 'center',
          dataIndex: 'isAllowDistributionMoney'
        },
        {
          title: '应收状态',
          align: 'center',
          dataIndex: 'shouldPayFlag',
          customRender: (text) => {
            if (text && text == 1) {
              return '已生成'
            } else {
              return '未生成'
            }
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 150,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }
      ],
      dictOptions: {},
      receivablePaymentLoading: false,
      cust_lxr: 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=0'
    }
  },
  computed: {
    formDisabled() {
      return true
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },

  watch: {
    'model.redistributionDtList'(val) {
      if (!val) return

      // 所有成员的预算工时之和
      this.model.expectWorkTime = val.reduce((total, item) => {
        return total + item.contractAmount
      }, 0)

      // 所有成员的人工成本之和
      this.model.workCost = val.reduce((total, item) => {
        return total + item.laborCost
      }, 0)
    },
    activeKey(key) {
      this.$forceUpdate()
    },
    taskId: {
      handler (val) {
        if (!val) {
          return false
        }
        // this.$set(this.modelDefault, 'taskId', val) // 任务档案编号
        // this.add(val)

        this.$set(this.model, 'createTime', moment().format('YYYY-MM-DD HH:mm:ss')) // 申请人
        this.$set(this.model, 'handlerId', this.userInfo().empId) // 申请人
        this.$set(this.model, 'handlerDeptId', this.userInfo().deptId) // 申请人
        this.$set(this.model, 'taskId', val) // 任务编号
        this.generatedFormNumber();

        // 获取任务编号
        if (val) {
          getAction(this.url.queryPageList, { id: val }).then((res) => {
            if (res.success) {
              var event = res.result.records[0]
              this.$set(this.model, 'categoryName', event.categoryName) // 业务分类
              this.$set(this.model, 'contractRate', event.contractRate) // 合同占比(%)
              this.$set(this.model, 'contractAmount', event.contractAmount) // 合同分配额(元)
              this.$set(this.model, 'taskType', '3') // 默认任务类型为其他

              this.$set(this.model, 'productTeam', event.productTeam) // 生产团队
            }
          })
        }
        this.visible = true;
      },
      immediate: true
    },
    projectNameId: {
      handler (val) {
        if (!val) {
          return false
        }
        getAction(this.url.erpOmcProjectQueryById, { id: val }).then((res) => {
          if (res.success) {
            var event = res.result
            // this.getQueryByEntity(event.id) // 获取履约保证金
            this.$set(this.model, 'projectName', event.projectName) // 项目名称
            this.$set(this.model, 'projectId', val) // 项目id
            this.$set(this.model, 'finalNo', event.finalNo) // 项目编号
            this.$set(this.model, 'teamName', event.teamName) // 经营团队
            this.$set(this.model, 'undertaker', event.undertaker) // 项目承接人
            this.$set(this.model, 'projectEstablishDate', event.projectEstablishDate) // 立项日期
            this.$set(this.model, 'signUnit', event.signUnit) // 签订单位
            this.$set(this.model, 'year', event.year) // 业绩归属年度
            this.$set(this.model, 'ownerUnit', event.ownerUnit) // 业主单位
            this.$set(this.model, 'contacts', event.contacts) // 联系人
            this.$set(this.model, 'contactTel', event.contactTel) // 联系方式
            this.$set(this.model, 'areaCode', event.areaCode) // 项目所在地址
            this.$set(this.model, 'projectAddress', event.projectAddress) // 项目所在详细地址
            this.$set(this.model, 'projectSource', event.projectSource) // 项目来源
            this.$set(this.model, 'estimatedContractAmount', event.estimatedContractAmount) // 预计合同额
            this.$set(this.model, 'estimatedContractcapitalChineseAmount', event.estimatedContractcapitalChineseAmount) // 预计合同额大写
            this.$set(this.model, 'establishReason', event.establishReason) // 立项事由及说明
            this.$set(this.model, 'attachment', event.attachment) // 项目附件
            this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + event.ownerUnit + '\'';
          }
        })
      },
      immediate: true
    }
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
    // 如果是流程中表单，则需要加载流程表单databw
    this.showFlowData();
    // 加载数据字典信息
    this.initDictConfig();
    this.customKey = 'memberColumns'
    this.memberColumnswidth = this.memberColumns.map(val => {
      return val.width
    })
  },
  methods: {
    handleDetail(record) {
      // 修改时将当前的值从remain中减去
      this.editRemain = record.je;
      this.$refs.paymentModal.edit(record);
      this.$refs.paymentModal.title = '查看';
      this.$refs.paymentModal.disableSubmit = true;
    },
    // 如果选择是，则需分配合同额自动变更为原始的合同分配额（元），合同分配额自动变为0
    handleChangeIsCancel(val) {
      if (val === '1') {
        this.model.separateContractAmount = this.model.contractAmount
        this.model.contractAmount = 0
      }
    },
    handleChangeSeparateContractAmount() {
      if (this.model.contractAmount && !isNaN(this.model.separateContractAmount)) {
        this.model.contractAmount -= this.model.separateContractAmount
        // 输入数字后，合同分配额会自动减少对应的金额，且需分配任务的合同占比也相应变小。需分配合同额不可大于需分配任务中原始的合同分配额。
        if (this.model.estimatedContractAmount) {
          this.model.contractRate = this.model.contractAmount / this.model.estimatedContractAmount
        }
      }
    },
    // 添加项目成员回调
    submitCallback(data) {
      let flag = true;
      for (let i = 0; i < this.model.redistributionDtList.length; i++) {
        if (this.model.redistributionDtList[i].id === data.id) {
          this.model.redistributionDtList.splice(i, 1, data);
          flag = false;
        }
      }
      if (flag) {
        this.model.redistributionDtList.push(data);
      }
      // this.model.redistributionDtList.push(model)
    },
    ...mapGetters(['userInfo']),
    // 获取单据编号
    generatedFormNumber() {
      getAction(this.url.generatedFormNumber, { prefix: 'RWZFP', subSystemCode: '05' }).then(res => {
        if (res.success) {
          this.$set(this.model, 'billNo', res.result)
        }
      })
    },

    // 选择项目名称
    async onChangeProjectName (item) {
      var event = await item.choseObj[0]
      if (!event) {
        this.$set(this.model, 'projectName', undefined) // 项目名称
        this.$set(this.model, 'bail', undefined) // 保证金
        this.$set(this.model, 'finalNo', undefined) // 项目编号
        this.$set(this.model, 'teamName', undefined) // 经营团队
        this.$set(this.model, 'undertaker', undefined) // 项目承接人
        this.$set(this.model, 'projectEstablishDate', undefined) // 立项日期
        this.$set(this.model, 'signUnit', undefined) // 签订单位
        this.$set(this.model, 'year', undefined) // 业绩归属年度
        this.$set(this.model, 'ownerUnit', undefined) // 业主单位
        this.$set(this.model, 'contacts', undefined) // 联系人
        this.$set(this.model, 'contactTel', undefined) // 联系方式
        this.$set(this.model, 'areaCode', undefined) // 项目所在地址
        this.$set(this.model, 'projectAddress', undefined) // 项目所在详细地址
        this.$set(this.model, 'projectSource', undefined) // 项目来源
        this.$set(this.model, 'estimatedContractAmount', undefined) // 预计合同额
        this.$set(this.model, 'estimatedContractcapitalChineseAmount', undefined) // 预计合同额大写
        this.$set(this.model, 'establishReason', undefined) // 立项事由及说明
        this.$set(this.model, 'attachment', undefined) // 项目附件

        this.$set(this.model, 'categoryName', undefined) // 业务分类
        this.$set(this.model, 'contractRate', undefined) // 合同占比(%)
        this.$set(this.model, 'contractAmount', undefined) // 合同分配额(元)

        this.$set(this.model, 'productTeam', undefined) // 生产团队
        this.$set(this.model, 'taskId', undefined) // 任务编号
        return false
      }
      this.getQueryByEntity(event.id) // 获取履约保证金
      this.$set(this.model, 'projectName', event.projectName) // 项目名称
      this.$set(this.model, 'finalNo', event.finalNo) // 项目编号
      this.$set(this.model, 'teamName', event.teamName) // 经营团队
      this.$set(this.model, 'undertaker', event.undertaker) // 项目承接人
      this.$set(this.model, 'projectEstablishDate', event.projectEstablishDate) // 立项日期
      this.$set(this.model, 'signUnit', event.signUnit) // 签订单位
      this.$set(this.model, 'year', event.year) // 业绩归属年度
      this.$set(this.model, 'ownerUnit', event.ownerUnit) // 业主单位
      this.$set(this.model, 'contacts', event.contacts) // 联系人
      this.$set(this.model, 'contactTel', event.contactTel) // 联系方式
      this.$set(this.model, 'areaCode', event.areaCode) // 项目所在地址
      this.$set(this.model, 'projectAddress', event.projectAddress) // 项目所在详细地址
      this.$set(this.model, 'projectSource', event.projectSource) // 项目来源
      this.$set(this.model, 'estimatedContractAmount', event.estimatedContractAmount) // 预计合同额
      this.$set(this.model, 'estimatedContractcapitalChineseAmount', event.estimatedContractcapitalChineseAmount) // 预计合同额大写
      this.$set(this.model, 'establishReason', event.establishReason) // 立项事由及说明
      this.$set(this.model, 'attachment', event.attachment) // 项目附件
      this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + event.ownerUnit + '\'';

      this.$set(this.model, 'categoryName', undefined) // 业务分类
      this.$set(this.model, 'contractRate', undefined) // 合同占比(%)
      this.$set(this.model, 'contractAmount', undefined) // 合同分配额(元)

      this.$set(this.model, 'productTeam', undefined) // 生产团队
      this.$set(this.model, 'taskId', undefined) // 任务编号
    },

    // 选择任务编号
    onTaskIdInput (item) {
      var event = item.choseObj[0]
      if (!event) {
        this.$set(this.model, 'categoryName', undefined) // 业务分类
        this.$set(this.model, 'contractRate', undefined) // 合同占比(%)
        this.$set(this.model, 'contractAmount', undefined) // 合同分配额(元)

        this.$set(this.model, 'productTeam', undefined) // 生产团队
        return false
      }
      // this.$set(this.model, 'categoryCode', event.categoryCode) // 业务分类编码
      this.$set(this.model, 'categoryName', event.categoryName) // 业务分类
      this.$set(this.model, 'contractRate', event.contractRate) // 合同占比(%)
      this.$set(this.model, 'contractAmount', event.contractAmount) // 合同分配额(元)

      this.$set(this.model, 'productTeam', event.productTeam) // 生产团队
    },

    getQueryByEntity(id) {
      // var params = {
      //   preProjectId: id,
      //   feeCategory: '2',
      //   bpmStatus: '3'
      // }
      // 查看项目保证金
      // getAction('/api/erp/finance/deposit/erpFinanceProjectDepositBill/queryByEntity', params).then((res) => {
      //   if (res.success) {
      //     let data = res.result
      //     this.$set(this.model, 'bail', data.remittanceAmount)
      //     // this.$set(this.validatorRules, 'collectionDate', [{ required: true, message: '请选择应收日期!' }]);
      //     // this.$set(this.validatorRules, 'paymentDesc', [{ required: true, message: '请填写款项节点说明!' }]);
      //   } else {
      //     this.$set(this.model, 'bail', undefined)
      //     // this.$delete(this.validatorRules, 'collectionDate');
      //     // this.$delete(this.validatorRules, 'paymentDesc');
      //   }
      // })
    },

    // 选择实施部门
    onExecuteDepartInput (item) {
      if (!item[0].minister) {
        this.$set(this.model, 'minister', undefined)
        return false
      }
      // 赋值部门负责人
      getAction('/api/erpmng/sys/api/queryUsersByUsernames', { usernames: item[0].minister }).then((res) => {
        var idsArr = []
        var ids = ''
        if (res && res.length) {
          res.map(value => {
            idsArr.push(value.empId)
          })
        }
        ids = idsArr.toString()
        this.$set(this.model, 'minister', ids)
      })
    },

    // 选择进度模板
    getTemplateList(data, obj) {
      if (data && data.length) {
        data.map(value => {
          value.id = this.getRandomNum()
        })
      }
      // 后端无良心，需要前端自己处理，当选择了“允许添加子节点”需要在每一个节点里面塞isAddChildNode值最后一个节点不用塞
      let isAddChildNode = obj.isAddChildNode;
      data.forEach((item, index) => {
        if (index === data.length - 1) {
          item.isAddChildNode = '0';
        } else {
          item.isAddChildNode = isAddChildNode;
        }
      });
      this.templateDataList = data;
    },

    // 获取唯一随机数
    getRandomNum() {
      let date = (new Date()).valueOf();// 获取时间戳
      let txt = '1234567890';// 生成的随机机器码
      let len = 19;// 机器码有多少位
      let pwd = '';// 定义空变量用来接收机器码
      for (let i = 0; i < len; i++) {
        pwd += txt.charAt(Math.floor(Math.random() * txt.length));// 循环机器码位数随机填充
      }
      return date + pwd
    },

    initDictConfig() {
      initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'productTeam', res.result)
        }
      })
      initDictOptions('ywfx_type').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'ywfl', res.result)
        }
      })
      initDictOptions('erp_employee_file,name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'projectMember', res.result)
        }
      })
    },
    add() {
      this.$set(this.modelDefault, 'createTime', moment().format('YYYY-MM-DD HH:mm:ss')) // 申请人
      this.$set(this.modelDefault, 'handlerId', this.userInfo().empId) // 申请人
      this.$set(this.modelDefault, 'handlerDeptId', this.userInfo().deptId) // 申请人
      this.$set(this.modelDefault, 'taskType', '3') // 默认任务类型为其他
      this.templateDataList = [] // 置空
      this.edit(this.modelDefault);
      this.generatedFormNumber();
    },
    async edit(record) {
      if (this.$refs.form) {
        await this.$refs.form.resetFields();
      }
      this.model = await Object.assign({}, record);
      this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + record.ownerUnit + '\'';
      // 获取项目数据
      if (this.model.projectId) {
        // this.getQueryByEntity(this.model.projectId) // 获取履约保证金
        getAction(this.url.erpOmcProjectQueryById, { id: this.model.projectId }).then((res) => {
          if (res.success) {
            var event = res.result
            this.$set(this.model, 'finalNo', event.finalNo) // 项目编号
          }
        })
      }
      if (this.model.id) {
        this.memberLoading = true
        getAction('/api/erp/task/erpOmcTaskRedistributionDt/queryByMainId', { mainId: this.model.id })
        .then(response => {
          this.model.redistributionDtList = response.result || []
        }).finally(() => {
          this.memberLoading = false
        })
      }
      if (record && record.taskId && record.id) {
        this.getReceivablePaymentList(record.taskId, record.id, '2')
      }

      this.visible = true;
      this[this.customKey].forEach((val, index) => {
        val.width = this[this.customKey + 'width'][index]
      })
    },
    // 获取开始的款项进度列表
    getReceivablePaymentList(taskId, mainId, type) {
      var params = {
        taskId: taskId
      }
      if (mainId) {
        params.mainId = mainId
      }
      if (type) {
        params.type = type
      }
      this.receivablePaymentLoading = true
      getAction('/api/erp/task/erpOmcTaskRedistribution/queryReceivablePayment', params).then(res => {
        if (res.success) {
          if (res.result && res.result.length > 0) {
            res.result.map((value, index) => {
              res.result[index].taskId_dictText = '' // 首先款项关联任务字段默认为空
              // 遍历planTaskList数组赋值给taskId_dictText
              res.result[index].taskId_dictText = value.planTaskVoList && value.planTaskVoList.length ? (value.planTaskVoList.map((obj) => { return obj.categoryName }).join(',')) : '';
            })
            this.progressNodeVoList = res.result
          } else {
            this.progressNodeVoList = []
          }
        }
      }).finally(() => {
        this.receivablePaymentLoading = false
      })
    },
    // 渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId };
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result);
          }
        });
      }
    },
    submitForm() {
      const that = this;
      // 触发表单验证
      // debugger
      // 若保存时，是否作废为是但需分配合同额不等于原始合同额，则无法保存并给出提示：作废需分配任务时，请将需分配任务的所有合同额全部分配出去
      if (this.model.isCancel === '1' && this.model.separateContractAmount !== this.model.contractAmount) {
        that.$message.warning('作废需分配任务时，请将需分配任务的所有合同额全部分配出去！');
        return
      }
      // 列表中所有新增分配任务的合同占比之和应该等于需分配合同额占预计合同额的百分比
      const listTotal = that.model.redistributionDtList.reduce((total, item) => {
        const contractRate = Number(item.contractRate) || 0;
        const decimalContractRate = new Decimal(contractRate);
        return total.plus(decimalContractRate);
      }, new Decimal(0)).toNumber(); // 解决浮点数导致两者不相等
      // 判断预计合同额是否为0，不为0则在校验
      if (that.model.estimatedContractAmount != '0' && that.model.estimatedContractAmount != null) {
        const compareTotal = Number(Number(that.model.separateContractAmount / that.model.estimatedContractAmount * 100).toFixed(2))
        if (listTotal !== compareTotal) {
          const text = `列表中所有新增分配任务的合同占比之和应该等于需分配合同额占预计合同额的百分比！当前需分配合同额占预计合同额的百分比为${compareTotal}%`
          that.$message.warning(text);
          return
        }
      }
      // 列表中所有新增分配任务的合同分配额之和应该等于需分配合同额
      const listTotal2 = this.model.redistributionDtList.reduce((total, item) => {
        return total + (Number(item.contractAmount) || 0)
      }, 0)
      if (listTotal2 !== Number(this.model.separateContractAmount)) {
        that.$message.warning('列表中所有新增分配任务的合同分配额之和应该等于需分配合同额！');
        return
      }

      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if (!this.model.id) {
            httpurl += this.url.add;
            method = 'post';
          } else {
            httpurl += this.url.edit;
            method = 'put';
          }

          let model = {};
          Object.assign(model, this.model)
          model.undertakerName = model.undertaker
          model.progressVoList = this.templateDataList // 任务进度
          httpAction(httpurl, model, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.$emit('ok');
            } else {
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
            // this.model.estimatedContractAmount = estimatedContractAmount;
          })
        }
      })
    },

    // 点击打印
    onPrint () {
      // eslint-disable-next-line no-unused-vars
      let print = new Print({
        el: '#taskContent',
        popTitle: '任务委托详情 · 禾美环保',
        endCallback() {

        }
      })
    },
    // 子表新增
    handleMemberAdd() {
      this.$refs.memberList.add();
      this.$refs.memberList.title = '新增';
      this.$refs.memberList.disableSubmit = false;
    },
    // 子表编辑
    handleMemberEdit(record) {
      this.$refs.memberList.edit(record);
      this.$refs.memberList.title = '修改';
      this.$refs.memberList.disableSubmit = false;
    },
    // 子表删除
    handleMemberDelete(id) {
      for (let i = 0; i < this.model.redistributionDtList.length; i++) {
        if (this.model.redistributionDtList[i].id == id) {
          this.model.redistributionDtList.splice(i, 1);
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.print_style{
  position: absolute;
  top: 0;
  z-index: -1111;
}
.icon{
  font-size: 45px;
}
</style>
<style>
  @import "../../../../../utils/print.css";
</style>
